package accs.product;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

public class CryptUtils {
	private static final DateFormat DATE_FORMAT=new SimpleDateFormat("yyyy.MM.dd");
	private static final long DAY=1000*60*60*24;
	
	private static String format(Date date) {
		return DATE_FORMAT.format(date);
	}
	
	
	private static boolean checkHash(String data, String hash, long date) {
		String computeHash=DigestUtils.sha512Hex(data+format(new Date(date)));
		return hash.equals(computeHash);
	}
	
	public static String encrypt(String data) throws UnsupportedEncodingException {
		return new StringBuilder(Hex.encodeHexString(data.getBytes("utf-8"))+DigestUtils.sha512Hex(data+format(new Date()))).reverse().toString();
	}
	
	public static String decrypt(String encData) throws UnsupportedEncodingException, DecoderException {
		encData=new StringBuilder(encData).reverse().toString();
		int index=encData.length()-128;
		String data=new String(Hex.decodeHex(encData.substring(0,index).toCharArray()),"utf-8");
		String hash=encData.substring(index);
		
		long now=System.currentTimeMillis();
		
		if(checkHash(data,hash,now) || checkHash(data, hash, now+DAY) || checkHash(data, hash, now-DAY)) {
			return data;
		} else {
			throw new IllegalAccessError();
		}
	}
	
//	public static void main(String[] args) throws UnsupportedEncodingException, DecoderException {
//		System.out.println(DigestUtils.sha512Hex("b791da4169e846cf0af727096eb6af5ad644f83cb77b7139f01be7f50bd9ba6c"));
//		
//		String data="hallo";
//		String enc=encrypt(data); System.out.println(enc);
//		String dec=decrypt(enc); System.out.println(dec);
//	}
}